/*
 * CRtpSink.h
 *
 *  Created on: 2016年4月29日
 *      Author: terry
 */

#ifndef CRTPSINK_H_
#define CRTPSINK_H_

#include "RtpSink.h"
#include "Jrtplib.h"
#include "TThread.h"
#include "TCriticalSection.h"
#include "OrderCache.h"
#include "Flowmeter.h"
#include "RtpPackager.h"
#include "RtpRecvState.h"


namespace av
{

typedef std::shared_ptr< RtpPackager >	RtpPackagerPtr;


class CRtpSink : public RtpSink, public jrtplib::RTPSession, public comn::Thread
{
public:
	CRtpSink();
	virtual ~CRtpSink();

	virtual int open(int port);

	virtual void close();

	virtual bool isOpen();

	virtual void setCallback(RtpSinkCallback cb, void* context);

	virtual void setFormat(int codec, int clockRate);

	virtual void setCacheSize(int size);

	virtual int getPort();


protected:
    virtual int run();
    virtual void doStop();
    virtual bool startup();
    virtual void cleanup();

protected:
    void onRtpPacket(jrtplib::RTPPacket* pPacket);
    bool filterPacket(jrtplib::RTPPacket* pPacket);

    void dealRtpPacket(jrtplib::RTPPacket* pPacket);


    MediaPacketPtr acquire(size_t length);

    void assignFrom(RtpPacket& pkt, jrtplib::RTPPacket* pPacket);
    bool joinPacket(RtpPacket& pkt, MediaPacket& pktOut);

    void printFlowStat();

    std::string getName();

    void fireMediaPacket(MediaPacket& packet);

    bool openSession(int port);

protected:
    comn::CriticalSection   m_cs;

    uint16_t    m_port;
    uint32_t    m_clockRate;
    RtpSinkCallback m_cb;
    void* m_context;
    int		m_codec;

    RtpRecvState   m_recvState;
    OrderCache     m_orderCache;

    int		m_payload;
    int		m_lastSeq;
    RtpPackagerPtr	m_packager;

    std::string m_name;
    Flowmeter   	m_flowmeter;
};



} /* namespace av */

#endif /* CRTPSINK_H_ */
